﻿using System.Collections.Generic;
using Entitas;
/// <summary>
/// based on the weapon equipped the collison entity that the weapon makes will exist for different time periods Ex.
/// A bow collision entity will last longer than a sword collision entity because the bow collison entity must have time to fly towards target
///  </summary>
class CollisionExpirationTimerSystem : ReactiveSystem<CollisionEntity>, ICleanupSystem
{
    CollisionContext collisionContext;
    public CollisionExpirationTimerSystem(Contexts contexts) : base(contexts.collision)
    {
        collisionContext = contexts.collision;
    }

    protected override void Execute(List<CollisionEntity> entities)
    {
        foreach (var e in entities)
        {
            e.ReplaceExpirationTime(e.expirationTime.value - .1f);
        }
    }

    protected override bool Filter(CollisionEntity entity)
    {
        return entity.hasExpirationTime;
    }

    protected override ICollector<CollisionEntity> GetTrigger(IContext<CollisionEntity> context)
    {
        return context.CreateCollector(CollisionMatcher.ExpirationTime.AddedOrRemoved());
    }
    /// <summary>
    /// if the timer of the collison reaches 0 then we destory the collison
    /// </summary>
    public void Cleanup()
    {
        foreach (var e in collisionContext.GetEntities())
        {
            if (e.expirationTime.value <= 0)
            {
                if (e.hasCollisionPositionListener)
                    e.RemoveCollisionPositionListener();
                if (e.hasBaseView)
                    e.baseView.value.DestoryView();
                e.Destroy();
            }
        }
    }
}

